import { Component, Input, Output, EventEmitter, ContentChildren, OnInit, QueryList, ContentChild, TemplateRef, OnChanges, SimpleChanges } from '@angular/core';
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError, RoutesRecognized } from '@angular/router';
import { CanDraw } from '../../common/draw/draw.component';
import { TableColumnComponent } from './column.component';

@Component({
  selector: 'es-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css', '../../app.component.css']
})
export class TableComponent implements OnInit, OnChanges {
  @ContentChild(TemplateRef) template: TemplateRef<TableColumnComponent>;
  //@ContentChildren(TableColumnComponent)
  //childCmps: QueryList<TableColumnComponent>;
  @Input() headers: Array<any>;
  @Input() datas: Array<any>;
  @Input() checkBox: boolean = false;
  @Output() sortEvent: EventEmitter<number> = new EventEmitter<number>();
  @Output() checkEvent: EventEmitter<any> = new EventEmitter<any>();
  nowSort: any = {};
  allSelect: boolean = false;
  checks: Array<boolean> = [

  ]
  checks_data = [];
  constructor(private router: Router) {

  }

  ngOnInit(): void {
    this.initCheck();
  }
  private initCheck() {
    this.checks = [];
    for (let d of this.datas) {
      this.checks.push(false);
    }
  }

  ngAfterContentInit() {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.datas && !changes.datas.firstChange) {
      this.allSelect = false;
      this.datas = changes.datas.currentValue;
      this.initCheck();
    }
  }

  allSelectCheck() {
    this.checks = [];
    for (let d of this.datas) {
      this.checks.push(this.allSelect);
    }
    this.sendCheckEvent();
  }

  checkSelect() {
    let allTrue = true;
    for (let c of this.checks) {
      if (!c) {
        allTrue = false;
      }
    }

    if (allTrue) {
      this.allSelect = true;
    } else {
      this.allSelect = false;
    }
    this.sendCheckEvent();
  }

  private sendCheckEvent(): any {
    this.checks_data = [];
    for (let i = 0; i < this.datas.length; i++) {
      if (this.checks[i]) {
        this.checks_data.push(this.datas[i]);
      }
    }
    this.checkEvent.emit(this.checks_data);
  }

  sort(header) {
    if (!header.canSort) {
      return;
    }

    if (this.nowSort.field == header.field) {
      if (this.nowSort.sort == 'asc') {
        this.nowSort.sort = 'desc'
      } else {
        this.nowSort.sort = 'asc';
      }
    } else {
      this.nowSort.field = header.field;
      this.nowSort.sort = 'asc';
    }

    if (this.sortEvent) {
      this.sortEvent.emit(this.nowSort);
    }

  }
}
